package com.masterclient.app.businessmodule.minemodule.withdraw;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.eoner.baselib.widget.navgation.FCNavigationBar;
import com.eoner.baselibrary.utils.StringsUtils;
import com.eoner.common.config.Config;
import com.eoner.managerlibrary.system.SystemConfigStorage;
import com.eoner.managerlibrary.user.UserDataManager;
import com.eoner.middlelib.router.intercept.FCBaseIntercept;
import com.eoner.middlelib.router.map.FCRouterPath;
import com.masterclient.app.R;
import com.masterclient.app.base.CashCommonDialog;
import com.masterclient.app.base.FCBusinessActivity;
import com.masterclient.app.businessmodule.minemodule.withdraw.contract.GainCashContract;
import com.masterclient.app.businessmodule.minemodule.withdraw.contract.GainCashPresenter;
import com.masterclient.app.businessmodule.minemodule.withdraw.widget.CashAgreementDialog;
import com.masterclient.app.businessmodule.minemodule.withdraw.widget.WithdrawCodeDialog;
import com.masterclient.app.businessmodule.settingmodule.bankcard.BankCardManageActivity;
import com.masterclient.app.businessmodule.settingmodule.bankcard.bean.NewBankCardBean;
import com.masterclient.app.modules.bridge.BridgeActivity;
import com.masterclient.app.utils.CaptchaUtil;

import java.lang.ref.WeakReference;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 作者：sean
 * 创建时间：2017/10/16 10:42
 * 功能说明：
 */
public class GainCashActivity extends FCBusinessActivity<GainCashPresenter> implements GainCashContract.View, TextWatcher {

    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.tv_all_money)
    TextView tvAllMoney;
    @BindView(R.id.et_apply_money)
    EditText etApplyMoney;

    @BindView(R.id.tv_apply)
    TextView tvApply;

    @BindView(R.id.bank_image)
    ImageView bank_image;
    @BindView(R.id.bank_name)
    TextView bank_name;
    @BindView(R.id.bank_card)
    TextView bank_card;
    @BindView(R.id.agree_checkbox)
    CheckBox agree_checkbox;
    @BindView(R.id.agree_layout)
    View agree_layout;
    @BindView(R.id.agree_btn)
    View agree_btn;
    @BindView(R.id.non_use_txt)
    View non_use_txt;
    @BindView(R.id.min_money)
    TextView minMoney;

    String amount, captcha, url;

    CaptchaUtil captchaUtil;
    @BindView(R.id.tv_cash_toast)
    TextView tvCashToast;

    private WeakReference<WithdrawCodeDialog>codeDialog;

    @Override
    protected int requireGetLayoutId() {
        return R.layout.activity_gain_cash;
    }

    @Override
    protected void requireSetCustomNavigationBar(FCNavigationBar navigationBar) {
        navigationBar.setTitle("提现").setRightBtnText("提现说明").setRightBtnTextColor(Color.parseColor("#999999"));
    }

    @Override
    protected void requireInitUIAndData(Bundle savedInstanceState) {
        amount = getBundleString("amount");
        url = getBundleString("url");
        tvMoney.setText("¥" + amount);

        SpannableString textSpanned = new SpannableString("（最小提现金额10元）");
        textSpanned.setSpan(new ForegroundColorSpan(Color.parseColor("#FFE79635")),
                7, 9, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        minMoney.setText(textSpanned);

        etApplyMoney.setFilters(new InputFilter[]{new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                String lastInputContent = dest.toString();
                if (lastInputContent.contains(".")) {
                    int index = lastInputContent.indexOf(".");
                    if (dend - index >= 2 + 1) {
                        return "";
                    }
                }
                return null;
            }
        }});

        etApplyMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (".".equals(s.toString())) {
                    etApplyMoney.setText("");
                }
                set_withdraw_btn_status();
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        captchaUtil = new CaptchaUtil(mContext, "提现");
        captchaUtil.setCaptchaListerner(new CaptchaUtil.CaptchaListerner() {
            @Override
            public void onSuccess(String ne) {
                mPresenter.getCaptcha(UserDataManager.getInstance().getMobile(), "withdraw", ne,true);
            }

            @Override
            public void onFailed() {
            }
        });
    }


    private void set_withdraw_btn_status() {

//        && "1".equals(sh_bank_card_status)
        if (!TextUtils.isEmpty(etApplyMoney.getText().toString())) {
            tvApply.setBackgroundResource(R.drawable.shape_round_f23051);
            tvApply.setTextColor(Color.parseColor("#FFFFFF"));
        } else {
            tvApply.setBackgroundResource(R.drawable.bankcard_bind_unable_click_bkg2);
            tvApply.setTextColor(Color.parseColor("#FFFFFF"));
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        mPresenter.getBankCard();
    }

    @Override
    protected void onNavigationLeftClick() {
        hideSoftInput(etApplyMoney);
        finish();
    }

    @Override
    protected void onNavigationRightClick() {
        super.onNavigationRightClick();
        if (bankCardData != null && !TextUtils.isEmpty(bankCardData.withdraw.ruleUrl)) {
            startActivitry(BridgeActivity.class, new String[][]{{"url", bankCardData.withdraw.ruleUrl}, {"title", "提现规则说明"}});
        }
    }

    @OnClick({R.id.tv_apply, R.id.tv_all_money, R.id.bankcard_layout, R.id.agree_btn})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_apply:
                String money = etApplyMoney.getText().toString().trim();
                if (!TextUtils.isEmpty(money)) {
                    if (bankCardData == null || TextUtils.isEmpty(bankCardData.bankcard.bankcardCertificationId)) {
                        showToast("请绑定一张银行卡");
                        return;
                    }
                    if (Double.valueOf(money) < 10) {
                        showToast("提现金额不可小于 10 元");
                        return;
                    }

                    if (Double.valueOf(money) > Double.valueOf(amount)) {
                        showToast("您的金额已超出可提现额度");
                        return;
                    }

                    if (!agree_checkbox.isChecked() && agree_layout.getVisibility() == View.VISIBLE) {
                        showToast("请同意提现协议");
                        return;
                    }

                    if (!UserDataManager.getInstance().getCheckIdCardStatus().equals("1")) {
                        display_ids_dialog(0);
                        return;
                    }

                    if ("0".equals(sh_bank_card_status)) {
                        display_ids_dialog(1);
                        return;
                    }

                    if (agree_layout.getVisibility() == View.VISIBLE) {
                        CashAgreementDialog cashAgreementDialog = new CashAgreementDialog(mContext);
                        cashAgreementDialog.setOnChooseListerner(new CashAgreementDialog.OnChooseListerner() {
                            @Override
                            public void cancel() {
                                cashAgreementDialog.dismiss();
                            }

                            @Override
                            public void confirm() {
                                cashAgreementDialog.dismiss();
                                //TODO:调验证码接口
                                if (SystemConfigStorage.getInstance().isOpenSlipPageCode()) {
                                    if (CaptchaUtil.CAPTCHA_NUMBER_TIMES >= Config.CAPTCHA_MAX_TIMES) {
                                        mPresenter.getCaptcha(UserDataManager.getInstance().getMobile(), "withdraw", "",true);
                                    } else {
                                        captchaUtil.start();
                                    }
                                } else {
                                    mPresenter.getCaptcha(UserDataManager.getInstance().getMobile(), "withdraw", "",true);
                                }
                            }
                        });
                        cashAgreementDialog.setAgree_url(agree_url);
                        cashAgreementDialog.show();
                    } else {
                        //TODO:调验证码接口
                        if (SystemConfigStorage.getInstance().isOpenSlipPageCode()) {
                            if (CaptchaUtil.CAPTCHA_NUMBER_TIMES >= Config.CAPTCHA_MAX_TIMES) {
                                mPresenter.getCaptcha(UserDataManager.getInstance().getMobile(), "withdraw", "",true);
                            } else {
                                captchaUtil.start();
                            }
                        } else {
                            mPresenter.getCaptcha(UserDataManager.getInstance().getMobile(), "withdraw", "",true);
                        }
                    }
                }
                break;
            case R.id.tv_all_money:
                etApplyMoney.setText(amount);
                break;
            case R.id.bankcard_layout:
                if (!UserDataManager.getInstance().getCheckIdCardStatus().equals("1")) {
                    display_ids_dialog(0);
                    return;
                }

                if ("0".equals(sh_bank_card_status)) {
                    display_ids_dialog(1);
                    return;
                }
                startActivitry(BankCardManageActivity.class, new String[][]{{"url", url}});
                break;
            case R.id.agree_btn:
                if (!TextUtils.isEmpty(agree_url))
                    startActivitry(BridgeActivity.class, new String[][]{{"url", agree_url}, {"title", "自由职业者合作协议"}});
                break;
            default:
        }
    }

    CashCommonDialog cashCommonDialog;

    private void display_ids_dialog(int type) {//0 未实名认证 1 实名认证银行卡不符
        String title = "";
        String confirm = "";
        if (type == 0) {
            title = "为保证您的资金账户安全，请上传您本人身份证用于账户安全保护";
            confirm = "去上传";
        } else if (type == 1) {
            title = "您并未绑定本人银行卡请重新绑卡";
            confirm = "去绑定";
        }
        cashCommonDialog = new CashCommonDialog(mContext, title, "取消", confirm, 1);
        cashCommonDialog.setOnChooseListerner(new CashCommonDialog.OnChooseListerner() {
            @Override
            public void cancel() {
                cashCommonDialog.dismiss();
            }

            @Override
            public void confirm() {
                cashCommonDialog.dismiss();
                if (type == 0) {
                    ARouter.getInstance().build(FCRouterPath.SETTING_AUTH_PATH).navigation(GainCashActivity.this, new FCBaseIntercept());
                } else if (type == 1) {
                    startActivitry(BankCardManageActivity.class, new String[][]{{"url", url}});
                }
            }
        });
        cashCommonDialog.show();
    }

    @Override
    public void applySuccess(String message) {
        if (codeDialog != null && codeDialog.get() != null && codeDialog.get().isShowing()) {
            codeDialog.get().dismiss();
        }
        Intent broadcast = new Intent();
        broadcast.setAction("refresh");
        sendBroadcast(broadcast);

        Intent intent = new Intent(GainCashActivity.this, WithdrawSuccessActivity.class);
        //intent.putExtra("amount", etApplyMoney.getText().toString().trim());
        intent.putExtra("amount", message);
        startActivityForResult(intent, 103);
        finish();
    }

    @Override
    public void applyFailed(String msg) {
        showToast(msg);
        if (codeDialog != null && codeDialog.get() != null && codeDialog.get().isShowing()) {
            codeDialog.get().initViews();
        }

    }

    @Override
    public void getCaptchaSuccess() {
        if (codeDialog != null && codeDialog.get() != null && codeDialog.get().isShowing()) {
            codeDialog.get().reStart();
        } else {
            //TODO:弹窗
            WithdrawCodeDialog dialog = new WithdrawCodeDialog(getActivity());
            dialog.setOnGetCaptchaClickListener(new WithdrawCodeDialog.WithdrawCodeDialogClickListener() {
                @Override
                public void getCaptchaClickListener(String ne) {
                    String phone = UserDataManager.getInstance().getMobile();
                    if (StringsUtils.isPhoneNum(phone)) {
                        mPresenter.getCaptcha(UserDataManager.getInstance().getMobile(), "withdraw", ne,false);
                    } else {
                        showToast("请输入正确的手机号");
                    }
                }

                @Override
                public void submitClickListener(String captcha) {
                    String money = etApplyMoney.getText().toString().trim();
                    mPresenter.balanceCashAdd(bankCardData.bankcard.bankcardCertificationId, money, captcha, agree_layout.getVisibility() == View.VISIBLE ? "1" : "0");
                }
            });
            dialog.show();
            dialog.setViewCodePage();
            codeDialog = new WeakReference<>(dialog);
        }

    }

    @Override
    public void getCaptchaFailed() {
        if (codeDialog != null && codeDialog.get() != null && codeDialog.get().isShowing()) {
            codeDialog.get().hiddenLoading();
        }
    }

    @Override
    public void getCaptchaFailed(String msg) {
        showToast(msg);
        if (codeDialog != null && codeDialog.get() != null && codeDialog.get().isShowing()) {
            codeDialog.get().hiddenLoading();
        }
    }

    @Override
    public void getBankCardFail(String msg) {
        bank_image.setImageResource(R.mipmap.insert_bank_icon);
        bank_card.setText("请先添加银行卡");
        bank_name.setText("银行卡");
    }

    NewBankCardBean bankCardData;

    String agree_url = "";

    String sh_bank_card_status;

    @Override
    public void showBankCard(NewBankCardBean data) {
        bankCardData = data;
        if (data != null) {
            if (data.withdraw != null) {
                if (!TextUtils.isEmpty(data.withdraw.ruleUrl)) {
                    url = data.withdraw.ruleUrl;
                }
//                if(!TextUtils.isEmpty(data.withdraw.desc)){
//                    tvCashToast.setText(data.withdraw.desc);
//                }
            }

            if (data.withdrawContract != null) {
                if (data.withdrawContract.isSigned) {
                    agree_layout.setVisibility(View.GONE);
                } else {
                    agree_layout.setVisibility(View.VISIBLE);
                }
                agree_url = data.withdrawContract.ruleUrl;
            }
            if (data.bankcard != null) {
                sh_bank_card_status = data.bankcard.bankcardStatus;
                if (data != null && !TextUtils.isEmpty(data.bankcard.bankcardNumber)) {
                    bank_image.setImageResource(R.mipmap.bank_default_icon);
                    bank_card.setText(data.bankcard.bankcardNumber);
                    bank_name.setText(data.bankcard.bankName);
                    if ("0".equals(data.bankcard.bankcardStatus)) {
                        non_use_txt.setVisibility(View.VISIBLE);
                    } else {
                        non_use_txt.setVisibility(View.GONE);
                    }

                } else {
                    bank_image.setImageResource(R.mipmap.insert_bank_icon);
                    bank_card.setText("请先添加银行卡");
                    bank_name.setText("银行卡");
                }
            }
        }
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        set_withdraw_btn_status();
    }

    @Override
    public void afterTextChanged(Editable editable) {

    }

}
